package com.forum.model.dao;

import java.util.List;

import org.hibernate.Session;

import com.forum.model.pojo.Section;
import com.forum.model.util.SessionManager;

public class SectionDAO implements GenericDAO<Section, String> {
	
	private Session session;
	
	@Override
	public boolean insert(Section section) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(section);
			session.getTransaction().commit();
			
			return true;
		} catch(Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean update(Section section) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(section);
			session.getTransaction().commit();

			return true;
		}catch(Exception e){
			System.out.println(e.getMessage());
		}finally{
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean delete(Section section) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(section);
			session.getTransaction().commit();
			
			return true;
		}catch(Exception e){
			System.out.println(e.getMessage());
		}finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public Section getObjectById(String name) {
		Section section = null;
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			section = (Section)session.get(Section.class, name);
			session.getTransaction().commit();
		}catch(Exception e){
			System.out.println(e.getMessage());
		}finally{
			SessionManager.closeSession(session);
		}
		return section;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Section> getAll() {
		List<Section> all = null;
		
		try{
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			all = (List<Section>) session.createQuery("from Section").list();
			session.getTransaction().commit();
		}catch(Exception e){
			System.out.println(e.getMessage());
		}finally{
			SessionManager.closeSession(session);
		}
		
		return all;
	}
}
